import Vue from 'vue'
import VueRouter from 'vue-router'
// token包,获取本地token
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const routes = [
  // 配置一级路由
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/',
    name: 'layout',
    redirect: 'welcome',
    component: () => import('@/views/layout/index.vue'),
    children: [
      // 1.用户列表
      {
        path: '/users',
        name: 'users',
        component: () => import('@/views/user/Userlist.vue')
      },
      // 2.角色列表
      {
        path: '/roles',
        name: 'roles',
        component: () => import('@/views/quanxian/Rolelist.vue')
      },
      // 3.权限列表
      {
        path: '/rights',
        name: 'rights',
        component: () => import('@/views/quanxian/Titlelist.vue')
      },
      // 4.商品列表
      {
        path: '/goods',
        name: 'goods',
        component: () => import('@/views/goods/Goodslist.vue')
      },
      // 5.分类参数
      {
        path: '/params',
        name: 'params',
        component: () => import('@/views/goods/Argument.vue')
      },
      // 6.分类参数
      {
        path: '/categories',
        name: 'categories',
        component: () => import('@/views/goods/Goodsort.vue')
      },
      // 7.订单列表
      {
        path: '/orders',
        name: 'orders',
        component: () => import('@/views/order/Orderlist.vue')
      },
      // 8.数据报表
      {
        path: '/reports',
        name: 'reports',
        component: () => import('@/views/data/Datalist.vue')
      },
      // 9.welcome
      {
        path: '/welcome',
        name: 'welcome',
        component: () => import('@/views/welcome/index.vue')
      },
      // 10,添加商品页面
      {
        name: '/addgoods',
        path: 'addgoods',
        component: () => import('@/views/goods/addgoods.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whilelist = ['/login']
// 路由token拦截
router.beforeEach((to, form, next) => {
  const token = getToken()
  // console.log(token);
  if (token) {
    next()
  } else {
    console.log(to.path)
    if (whilelist.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

// 重写router原型对象的Push
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

export default router
